<?php
class SysadminModel extends CommonModel {
	public function __construct(){
		parent::__construct();
	}
/*
	 *@page 第几页
	 *@per_page 每一页显示的数据 
	 */
	public function querySysadminList($p =  1 ,$per_page , $where = array() ){
		$getwhere = " " ;
		
		if(isset($where['nick']) && $where['nick']){
			$getwhere.=" and a.nick like '%{$where['nick']}%' ";
		}
		if(isset($where['username']) && $where['username']){
			$getwhere.=" and a.username like '%{$where['username']}%' ";
		}
		if(isset($where['gid']) && $where['gid']){
			$getwhere.=" and a.gid = '{$where['gid']}' ";
		}
		$colum = $this->query_columns(C('DB_PREFIX')."admin_user");
		$field = "a.".$where['field'] ;
		if(!in_array($where['field'], $colum)){
			$field = "a.".$colum[0] ;
		}
		$orderby = $where['orderby'] ;
		if(!in_array(strtolower($orderby), array('asc' , 'desc' ))){
			$orderby = "asc" ;
		}
		import('Library.Page' , APP_PATH);
		$data = array() ;
		$sql_count = "SELECT COUNT(*) AS tt FROM ".C('DB_PREFIX')."admin_user  as a left join ".C('DB_PREFIX')."admin_role  as b on a.gid = b.id  where 1 = 1   {$getwhere} ";
		$totalData = M()->query($sql_count);
		$total = $totalData[0]['tt'];
		$page = new Page($total,$per_page);
		$page_string =  $page->show();
		if($p <=0 ){
			$p = 1 ;
		}
		$limit = ($p-1)*$per_page;
		$limit.=",{$per_page}";
		
		$sql_user = "SELECT a.* , b.rolename FROM ".C('DB_PREFIX')."admin_user  as a left join ".C('DB_PREFIX')."admin_role  as b on a.gid = b.id  where 1 = 1 {$getwhere} order by {$field} {$orderby}  limit {$limit} ";
		//echo $sql_user;
		$list = M()->query($sql_user);
		
		foreach($list as $k=>$v){
			$list[$k]['status'] = ($v['status'] == 1 )?"开启":'<font color="red">关闭</font>';
			$list[$k]['gid'] = ($v['super_admin'] == 1 )?"<font color='red'>管理员</font>" :$v['rolename'] ;  
			$list[$k]['super_admin'] = ($v['super_admin'] == 1 )?"<font color='red'>管理员</font>":'不是' ; 
		}
		$data = array(
			'list'=>$list , 
			'page_sting'=>$page_string		
		);
		return $data ;
	}
	//添加系统用户
	public function add_sysadmin($data){
		if($data['gid']<=0 && $data['super_admin']!=1 ){
			return array('status'=> 0 , 'message'=> '请选择用户组' ) ;
		}elseif(abslength($data['username'])<6 || abslength($data['username'])>16){
			return array('status'=> 0 , 'message'=> '用户名长度必须在6-16之间' ) ;
			
		}elseif($data['passwd'] == "" || utf8_str($data['passwd']) != 1){
			return array('status'=> 0 , 'message'=> '密码不能为空必须是英文' );
			
		}
		$data['passwd'] = md5($data['passwd']);
		if($data['super_admin'] == 1 ){
			$data['gid'] = 0 ;
		}
		$info = M("Admin_user")->where("username = '{$data['username']}' ")->find();
		if(is_array($info) && $info){
			return array('status'=> 0 , 'message'=> '用户已经存在' );
		}
		$insertId = M("Admin_user")->add($data);
		
		$sql =  M("Admin_user")->getLastSql();
		if($insertId>=1){
			write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),1,"添加用户为{$data['username']}成功");
			return array('status'=> 1 , 'message'=> 'success' );
		}else{
			write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),0,"添加用户为{$data['username']}失败");
			return array('status'=> 0 , 'message'=> '服务器繁忙 添加用户失败' );
			
		}
	}
	//修改管理员的密码
	public function edit_passwd($data = array() ){
		if($data['passwd'] == "" || utf8_str($data['passwd']) != 1){
			return array('status'=> 0 , 'message'=> '密码不能为空必须是英文' );
		}
		$passwd = md5($data['passwd']);
		$num = M("Admin_user")->where("id = '{$data['id']}'")->save(array('passwd'=>$passwd));
		$sql_edit = M("Admin_user")->getLastSql();
		if($num>=1){
			write_action_log($sql_edit,getModuleAction(),$this->username,get_client_ip(),1,"修改用户id是{$data['id']}的密码成功");
			return array('status'=>1 , 'message'=>'操作成功' );
		}else{
			write_action_log($sql_edit,getModuleAction(),$this->username,get_client_ip(),0,"修改用户id是{$data['id']}的密码失败");
			return array('status'=>0 , 'message'=>'修改失败 你可能么有修改数据' );
		}
	}	
	public function judge($id){
		if(!in_array($this->username, C("super_admin"))){
			return array('status'=>0 , 'message'=>'对不起你没权限进行设置用户的权限信息，必须是超级管理员才可以设置' );
		}
		
		$info_ = $this->getInfoById($id);//修改后台用户的基本信息
		if(empty($info_)){
			return array('status'=>0 , 'message'=>'没有此用户的信息' );
		}
		$list = $this->getGroup();
		$perm_array = M("Admin_nav")->field("id,name,pid as parentid,url ")->order("disorder,id desc")->select();
		$result = array();
		if($perm_array){
			foreach($perm_array as $k=>$v){
				$result[$v['id']]  = $v ;
			}
		}
		$result = genTree9($result,'id','parentid','childs');
		$options =  getChildren($result);
			$perms = $info_['perm'];
			$perm_array_exists = array();
			if($perms){
				$perm_array_exists = unserialize($perms);
			}
			$temp = array();
			if($options && $perm_array_exists){
				foreach($options as $o_=>$v_){
					if(in_array($v_['url'],$perm_array_exists)){
						$temp[$v_['url']] = $v_['name'];
					}
				}
			}
			
			unset($perm_array_exists);
			$perm_array_exists = $temp ;
			return array(
				'status'=>1 ,
				'info'=>$info_,
				'list'=>$list,
				'options'=>$options,
				'perm_array_exists'=>$perm_array_exists
			);
	}
	//查询所有的组
	public function getGroup(){
		return $list = M("Admin_role")->where("status = '1' ")->select();
	}
	
	//处理用户设置权限
	public function doSetPerminsions($data){
		$perms = $data['perms'] ;;
		$nick = $data['nick'] ;
		$status = intval($data['status']);
		$super_admin = intval($data['super_admin']) ;
		$gid  =intval($data['gid']);
		$id = intval($data['id']);
		$perms_string = '' ;
		$perms_array = array();
		if($perms){
			for($i = 0 ;$i <count($perms); $i++){
				if($perms[$i] == ''){
					continue ;
				}
				$perms_array[] = $perms[$i];
			}
			if($perms_array){
				$perms_string = serialize($perms_array);
			}
		}
		$update_data = array(
			'nick'=>$nick , 
			'status'=>$status,
			'super_admin'=>$super_admin		
		);
		if(!$super_admin){
			$update_data['gid'] = $gid ;
		}
		if(!$super_admin){
			$update_data['perm'] = $perms_string ;
		}else{
			$update_data['perm'] = '' ;
		}
		$num = M("Admin_user")->where("id = '{$id}' ")->save($update_data);
		$sql_edit = M("Admin_user")->getLastSql();;
		//echo $sql_edit;die();
		if($perms_array && !$super_admin){
			$this->make_cache($id , $perms_array);
		}
		if($num>=1){
			write_action_log($sql_edit,getModuleAction(),$this->username,get_client_ip(),1,"修改用户{$nick}成功");
			return array('status'=>1 , 'message'=>'操作成功' );
		}else{
			write_action_log($sql_edit,getModuleAction(),$this->username,get_client_ip(),0,"修改用户{$nick}失败");
			return array('status'=>0 , 'message'=>'操作失败' );
		}
	
	}	
	//生成缓存
	private function make_cache($admin_id , $perm_array){
		if(!is_writable(C("role_cache_path"))){
			exit("目录".C("role_cache_path")."不可写");
		}
		$perm_array = delete_str_($perm_array);
		$configfile = C("role_cache_path")."/cache_admin_{$admin_id}.inc.php";
		$fp = fopen($configfile,'w');
		$time = date("Y-m-d", time() );
		flock($fp,3);
		fwrite($fp,"<"."?php\r\n");
		fwrite($fp,"/*用户特殊的权限缓存*/\r\n");
		fwrite($fp,"/*author wangjian*/\r\n");
		fwrite($fp,"/*time {$time}*/\r\n");
		fwrite($fp,"\$admin_perm_array = array(\r\n");
		foreach($perm_array as $k=>$v){
			fwrite($fp,"'{$k}' => '{$v}',\r\n");
		}
		fwrite($fp,");\r\n");
		fwrite($fp,"?".">");
		fclose($fp);
	}		
	//根据Id查询系统用户信息
	public function getInfoById($id){
		$info = M("Admin_user")->where("id = '{$id}' ")->find();
		return $info ;
	}
	//根据session_id 和用户的ID 查询是否存在
	public function getDataBySessionIdUserid($session_id , $userid){
		$info = M("Admin_session")->where("userid = '{$userid}' and session_id = '{$session_id}'")->find();
		if(!$info){
			return false ;
		}
		return true  ;
	}
	

}
